package com.stms.action;

import com.alibaba.fastjson.JSONObject;
import com.stms.pojo.Staff;
import com.stms.service.StaffService;
import com.stms.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/staff")
public class StaffController {
    @Autowired
    public StaffService staffService;

    private Integer count;

    @PostMapping("/addStaff")
    public Result addStaff(@RequestBody Staff staff){
        if(staffService.addStaff(staff)){
            return new Result(200,"add success");
        }else{
            return new Result(500,"add fail");
        }
    }

    @PostMapping("/editStaff")
    public Result editStaff(@RequestBody Staff staff){
        if(staffService.editStaff(staff)){
            return new Result(200,"edit success");
        }else{
            return new Result(500,"edit fail");
        }
    }

    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody JSONObject obj){
        try{
            String staffIds = (String)obj.get("staffIds");
            staffService.deleteBatch(staffIds);
            return new Result(200,"delete success");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(500,"error");
        }
    }

    @PostMapping("/fuzzyQuery")
    public Map fuzzyQuery(Integer pageNum, Integer pageSize, String direction, Staff staff){
        Page<Staff> page = staffService.fuzzyQuery(pageNum,pageSize,direction,staff);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("data",page);
        return map;
    }

    @CrossOrigin
    @PostMapping("/findByPage")
    public Map findByPage(Integer pageNum,Integer pageSize){
        if(count!=null&&pageNum>=count){
            pageNum=count;
        }

        Page<Staff> page = staffService.findByPage(pageNum,pageSize);
        count = page.getTotalPages();
        Map<String,Object> map = new HashMap<>();
        map.put("data",page);
        return map;
    }
}
